<?php

namespace app\api\model\music;

use app\logic\model\music\MusicLogicModel;
use app\logic\model\music\MusicSkewerLogicModel;
use app\logic\model\user\UserLogicModel;
use app\logic\single\MusicSingle;

class MusicSkewerApiModel extends MusicSkewerLogicModel
{


    public function getSelect(array $where=[],string $field='*',string $order='id desc',int $limit=15){
        return $this->where($where)
            ->field($field)
            ->order($order)
            ->limit($limit)
            ->select();
    }

    public function getToday($where, string $field,string $order='id desc',int $limit=15)
    {
        return $this->where($where)
            ->field($field)
            ->order($order)
            ->limit($limit)
            ->select();
    }

    public function getApiList(array $param, array $where=[], string $field='*', $page=1, $limit=15,string $order='sort desc')
    {
        $query=$this->where($where)
            ->where(function ($q) use ($param){
                $ids_where=[];
                $ids_check=-1;
                $music_id_arr=[];
                if(check_request($param,'title')){
                    $q->whereLike("title","%{$param['title']}%");
                }
                if(check_request($param,'type_id')){
                    $q->whereIn("type_id",$param['type_id']);
                }
                if(check_request($param,'status')){
                    $q->where("status",$param['status']);
                }
                if(check_request($param,'writer_id')){
                    $music_id_arr = MusicLogicModel::getIdsByUserId($param['writer_id'])?:[-1];
                }
                if(check_request($param,'writer_name')){
                    $user_id_arr =UserLogicModel::getIdsByWriterName($param['writer_name']);
                    $music_id_arr = MusicLogicModel::getIdsByUserId($user_id_arr)?:[-1];
                }
                if(!empty($music_id_arr)){
                    $q->whereIn("music_id",array_unique($music_id_arr));
                }
            })->with(['music'])->visible(
                ['music'=>['title','url']]
            );
        $list = $query->field($field)->order($order)
            ->page($page,$limit)->select();
        $count = $query->count();
        if($count>0){
            $list = $this->getWriterByMusic($list->toArray());
        }
        return [$list,$count];
    }

    public function details($id, string $field)
    {
        $info = $this->getFindById($id,$field);
        if(empty($info)){
            return false;
        }
        [$info['music'],$info['writer']] = MusicSingle::getInstance()->getMusicAndUser($info['music_id']);
        return $info;
    }
}